package com.heima.comment.service.impl;

import com.heima.comment.service.ManagementService;
import com.heima.common.exception.CustException;
import com.heima.model.comment.dto.ComDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vos.ManagementRepayVo;
import com.heima.model.comment.vos.ManagementVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.comment.dto.ManagementDTO;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ManagementServicelmpl implements ManagementService {
    @Autowired
    MongoTemplate mongoTemplate;
    /**
     * 查询评论列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(ManagementDTO dto) {
        //1.校验参数
            //  登录
        ApUser user = AppThreadLocalUtils.getUser();
        if(user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"请先登录");
        }
        if (dto.getSize() == null || dto.getSize() == 0) {
            Integer size = 10;
            dto.setSize(size);
        }
        if (dto.getMinDate() == null) {
            dto.setMinDate(new Date());
        }
        //2.根据用户id获得所有评论信息
        Query query = Query.query(Criteria.where("authorId").is(user.getId()));
        query.limit(dto.getSize());
        Sort newSort = Sort.by(Sort.Direction.DESC, "createdTime");//时间降序
        query.with(newSort);// 排序
        List<ManagementVo> managements = mongoTemplate.find(query, ManagementVo.class);
        //3.遍历评论信息
        for (ManagementVo managementVo : managements) {
            //3.1根据评论id获得回复列表
            Query queryRepay = Query.query(Criteria.where("commentId").is(managementVo.getId()));
            query.limit(10);//截取
            Sort sort = Sort.by(Sort.Direction.DESC, "createdTime");//时间降序
            query.with(sort);// 排序
            List<ManagementRepayVo> managementRepayVos = mongoTemplate.find(queryRepay, ManagementRepayVo.class);
            managementVo.setReplies(managementRepayVos);
        }
        //4.封装返回结果
       return ResponseResult.okResult(managements);
    }

    /**
     * 根据评论id删除相关行为
     * @param dto
     * @return
     */
    @Override
    public ResponseResult deleteList(ComDTO dto) {
        //1.校验参数id
        if(dto.getId() ==null ||"".equals(dto.getId())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"id不能为空");
        }
        //登录
        ApUser user = AppThreadLocalUtils.getUser();
        if(user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2.根据评论id获得回复列表
        Query commentId = Query.query(Criteria.where("commentId").is(dto.getId()));
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(commentId, ApCommentRepay.class);
        //2.1根据id删除点赞信息
        for (ApCommentRepay apCommentRepay : apCommentRepays) {
            Query commentRepayId = Query.query(Criteria.where("commentRepayId").is(apCommentRepay.getId()));
            mongoTemplate.remove(commentRepayId, ApCommentRepayLike.class);
        }
        //2.2删除回复列表
        DeleteResult remove = mongoTemplate.remove(commentId, ApCommentRepay.class);
        log.info("删除回复个数：{}",remove.getDeletedCount());
        //3.根据评论id删除点赞行为信息
        DeleteResult remove1 = mongoTemplate.remove(commentId, ApCommentLike.class);
        log.info("删除评论点赞个数：{}",remove1.getDeletedCount());
        //4删除此评论
        Query query = Query.query(Criteria.where("id").is(dto.getId()));
        DeleteResult remove2 = mongoTemplate.remove(query,ApComment.class);
        log.info("删除评论个数：{}",remove2.getDeletedCount());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 评论置顶
     * @param dto
     * @return
     */
    @Override
    public ResponseResult changeTop(ComDTO dto) {
        //1.校验参数 id   登录
        if(dto.getId()==null ||"".equals(dto.getId())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"id不能为空");
        }
        ApUser user = AppThreadLocalUtils.getUser();
        if(user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2.根据评论id获得评论信息
        Query query = Query.query(Criteria.where("id").is(dto.getId()));
        //3.修改flage，将他设置为2
        Update update = new Update();
        update.set("flag",(short)2);
        //保存修改
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, ApComment.class);
        log.info("修改成功：{}",updateResult.getMatchedCount());
        //返回封装结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
